package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static com.sky.constant.MessageConstant.ORDER_TIME_OUT;
import static com.sky.entity.Orders.*;


/**
 * 自定义定时任务类:处理订单状态
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;

    /**
     * 处理超时订单
     * 每分钟执行一次
     */
    //@Scheduled(cron = "0 * * * * ? ")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        //1. 查询下单后15内未支付的订单
        LocalDateTime now = LocalDateTime.now();
        List<Orders> orderList = orderMapper.getByStatusAndOrderTime(PENDING_PAYMENT, now.plusMinutes(-15));

        //2. 修改订单状态为【已取消】
        if (orderList!=null&&orderList.size()!=0) {
            orderList.forEach(order->{
                order.setStatus(CANCELLED);
                order.setCancelReason(ORDER_TIME_OUT);  //设置取消原因【订单超时】
                order.setCancelTime(now);

                //3. 更新订单数据
                orderMapper.update(order);
            });
        }
    }

    /**
     * 每天凌晨1点处理派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder(){
        log.info("定时处理派送中的订单：{}",LocalDateTime.now());
        //1. 查询还在派送中且时间是上一个工作日的订单
        //now.plusMinutes(-60)==昨天的24时
        LocalDateTime now = LocalDateTime.now();
        List<Orders> orderList = orderMapper.getByStatusAndOrderTime(PENDING_PAYMENT, now.plusMinutes(-60));

        //2. 修改订单状态为【已完成】
        if (orderList!=null&&orderList.size()!=0) {
            orderList.forEach(order->{
                order.setStatus(COMPLETED);

                //3. 更新订单数据
                orderMapper.update(order);
            });
        }
    }
}
